package com.buaa.rental.Util;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

public class ImgUtil
{

	private static final Logger logger = LoggerFactory.getLogger(ImgUtil.class);
	/**
	 * 返回唯一标识符
	 *
	 * @return String
	 **/
	public static String getUUID()
	{
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String getSuffix(String fileName)
	{
		return fileName.substring(fileName.lastIndexOf('.'));
	}

	public static String getFileName(String fileOriginName)
	{
		return getUUID() + getSuffix(fileOriginName);
	}

	/**
	 * 将文件保存到/resources/public/photos/下面，以便静态访问
	 *
	 * @param file 需要保存的文件
	 * @return String 静态文件访问的url
	 **/
	public static String saveFile(MultipartFile file) throws IOException
	{
		String nname = getFileName(file.getOriginalFilename());
		String resource = ResourceUtils.getURL("classpath:").getPath();
		File path = new File(resource);
		if (!path.exists())
		{
			path = new File("");
		}
		logger.error("nmd"+path.getAbsolutePath());
		File dest = new File(path.getAbsolutePath() + "/public/photos/" + nname);
		if (!dest.getParentFile().exists())
		{

			dest.getParentFile().mkdirs();
		}
		logger.error("nmd"+dest.getAbsolutePath());
		file.transferTo(dest);
		return "photos/" + nname;
	}

}
